<?php
/**
 * Represent user model
 */
class User_m extends CI_Model
{
	function __construct()
	{
		parent::__construct();
		$this->load->helper('security');
	}

    /**
	 * Authenticate user
	 */
    function authenticate ( $username, $password ) {
	    $enc_password = md5($password);
		$query = $this->db->query("SELECT * FROM oregano_user WHERE `username`='$username' and `password` =  '$enc_password' LIMIT 1");
	    $row =  $query->row_array();
		if($row){
		    if($row['activated']==0){
			    // Not activated yet
				return -2;
			}
		    return 0;
		}
		return -1;
	}

    /**
	 * Register
	 */ 
	function register( $username, $email, $password, $first_name, $last_name, $gender, $phone, $address1, $address2, $city, $province,
	         $country, $postal_code, $facebook, $twitter, $website){
			 
		$data = array(
		             'username' => $username,
					 'password' => md5($password),
					 'admin' => 'N',
					 'activation_code' => md5(time()),
					 'activated' => 0,
					 'email' => $email
		        );
 	    $query = $this->db->insert_string('oregano_user', $data);
		$this->db->query($query);
		$generated_id = $this->db->insert_id();		 
		
		$data = array(
		            'user_id' => $generated_id,
					'first_name' => $first_name,
					'last_name' => $last_name,
					'phone' => $phone,
					'address1' =>  $address1,
					'address2' =>  $address2,
					'city' => $city,
					'province_state' => $province,
					'country' => $country,
					'postal_code' => $postal_code,
					'facebook' => $facebook,
					'twitter' => $twitter,
					'website' => $website,
					'gender' => $gender
				);
		$query = $this->db->insert_string('oregano_user_fields', $data);
		$this->db->query($query);		
	}
	
	/**
	 * 
	 */
	function find_user_by_username( $username ){
		$query = $this->db->query("SELECT a.*, b.* FROM oregano_user a INNER JOIN oregano_user_fields b on a.id=b.user_id WHERE `username`='$username' LIMIT 1");
		return  $query->row_array();
	} 
}
?>